<template>
    <div class="app-container">
        <el-form :inline="true" :model="formInline" class="demo-form-inline" style="margin-top: 2%">
            <el-row :gutter="0" >
                <el-col :span="6">
                    <el-form-item label="用户名">
                        <el-input size="mini" v-model="searchParams.userName" placeholder="用户名" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="手机号">
                        <el-input size="mini" v-model="searchParams.phone" placeholder="手机号" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="邮箱">
                        <el-input size="mini" v-model="searchParams.email" placeholder="电子邮件" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item  size="mini"label="创建时间">
                       <!-- <el-input v-model="searchParams.createTime" placeholder="创建时间"></el-input>-->
                        <el-date-picker
                                v-model="searchParams.createTime"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="创建时间">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
      <el-row >
          <el-button  type="primary" @click="onSubmit" size="small" icon="el-icon-search" v-hasPermi="['sys:user:search']">搜索</el-button>
          <el-button  type="success" @click="add" size="small" icon="el-icon-plus"  v-hasPermi="['sys:user:add']">新增</el-button>
          <el-button  type="danger" @click="deleteBatch" size="small" icon="el-icon-delete" :disabled="deleteFlag" v-hasPermi="['sys:user:deletebatch']">批量删除</el-button>
          <el-button  type="info" @click="importExcel" size="small" icon="eel-icon-upload2" v-hasPermi="['sys:user:import']">导入</el-button>
          <el-button  type="warning" @click="exportExcel" size="small" icon="el-icon-download"  v-hasPermi="['sys:user:export']">导出</el-button>

      </el-row>

        <template>
            <el-table
                    :data="userList"
                    v-loading="loading"
                    element-loading-text="拼命加载中"
                    @selection-change="handleSelectionChange"
                    style="width: 100%">
                <el-table-column
                        type="selection"
                        width="55">
                </el-table-column>
                <el-table-column
                        label="用户名"
                        prop="userName"
                        width="280">
                   <!-- <template slot-scope="scope">
                        <span style="margin-left: 10px">{{ scope.row.date }}</span>
                    </template>-->
                </el-table-column>
                <el-table-column
                        label="电子邮箱"
                        prop="email"
                        width="280">
                </el-table-column>
                <el-table-column
                        label="手机"
                        prop="phonenumber"
                        width="280">
                </el-table-column>
                <el-table-column
                  label="昵称"
                  prop="nickName"
                  width="280">
                </el-table-column>
               <!-- <el-table-column
                        label="是否冻结"
                        prop="isFreeze"
                        width="180">
                </el-table-column>-->
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button
                                size="mini"
                                @click="handleEdit(scope.$index, scope.row)" v-hasPermi="['sys:user:edit']">编辑</el-button>
                       <!-- <div>
                            {{scope.row}}
                            {{scope.row.isAdministrator ==='0'}}
                        </div>-->
                        <!--<template v-if="!scope.row.isAdministrator==='0'">-->
                            <el-button
                                    size="mini"
                                    type="danger"
                                    v-if="scope.row.isAdmin ===0?deleteShowFlag=false:true"
                                    @click="handleDelete(scope.$index, scope.row)" v-hasPermi="['sys:user:delete']">删除</el-button>
                       <!-- </template>-->

                    </template>
                </el-table-column>
            </el-table>
        </template>

        <div class="page">

          <Pagination v-show="total>0"
                      :total="total"
                      :page.sync="searchParams.pageNum"
                      :limit.sync="searchParams.pageSize"
                      @pagination="getUserLists" />
        </div>
        <el-dialog
                title="新增用户"
                :visible.sync="addFlag"
                width="500px" append-to-body>
            <el-form ref="form" :model="userForm" :rules="rules" label-width="80px">
                <el-row>

                    <el-col :span="12">
                        <el-form-item label="用户名" prop="userName">
                            <el-input
                                    placeholder="请输入用户名称"
                                    v-model="userForm.userName"
                                    clearable>
                            </el-input>
                        </el-form-item>
                    </el-col>

                  <el-col :span="12">
                    <el-form-item label="用户昵称" prop="nickName">
                      <el-input
                        placeholder="请输入用户昵称"
                        v-model="userForm.nickName"
                        clearable>
                      </el-input>
                    </el-form-item>
                  </el-col>
                    <el-col :span="12">
                        <el-form-item label="密码" prop="password">
                            <el-input
                                    placeholder="请输入密码"
                                    v-model="userForm.password"
                                    show-password
                                    clearable>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <!--<el-col :span="12">
                        <el-upload
                                class="avatar-uploader"
                                action="https://jsonplaceholder.typicode.com/posts/"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                            <img v-if="imageUrl" :src="imageUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-col>-->
                    <el-col :span="12">
                        <el-form-item label="性别" >
                            <el-select v-model="userForm.sex" clearable placeholder="请选择">
                                <el-option label="男" value="0"></el-option>
                                <el-option label="女" value="1"></el-option>
                              <el-option label="未知" value="2"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                  <!--  <el-col :span="12">
                        <el-form-item label="管理员" prop="isAdministrator">
                            <el-select v-model="userForm.isAdministrator" clearable placeholder="请选择">
                                <el-option label="是" value="0"></el-option>
                                <el-option label="否" value="1"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>-->
                    <el-col :span="12">
                        <el-form-item label="邮箱" prop="email">
                            <el-input
                                    placeholder="请输入邮箱地址"
                                    v-model="userForm.email"
                                    clearable>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="电话" prop="phonenumber">
                            <el-input
                                    placeholder="联系方式"
                                    v-model="userForm.phonenumber"
                                    clearable>
                            </el-input>
                        </el-form-item>
                    </el-col>
                  <el-col :span="12">
                    <el-form-item label="角色">
                      <el-select v-model="roles" multiple placeholder="请选择" @change="selectRoles"  value-key="value" >
                        <el-option
                          v-for="item in options"
                          :key="item.value"
                          :label="item.label"
                          :value="item">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="备注" prop="remark">
                      <el-input
                        type="textarea"
                        autosize
                        placeholder="备注"
                        v-model="userForm.remark">
                      </el-input>
                    </el-form-item>
                  </el-col>

                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addFlag = false">取 消</el-button>
                <el-button type="primary" @click="addSubmit">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog
                title="导入用户"
                :visible.sync="exportFlag"
                width="500px" append-to-body>
            <el-form  label-width="80px">
                <el-upload
                        class="upload-demo"
                        drag
                        action="#"
                        :before-upload="beforeUpload"
                        multiple>
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip" slot="tip">
                        <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
                    </div>
                    <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
                </el-upload>
            </el-form>
            <span slot="footer" class="dialog-footer">
               <!-- <el-button @click="exportFlag = false">取 消</el-button>
                <el-button type="primary" @click="excelSubmit">确 定</el-button>-->
            </span>
        </el-dialog>
        <el-dialog
                title="编辑用户"
                :visible.sync="editFlag"
                width="500px" append-to-body>
            <el-form ref="userForm" :model="userForm" :rules="rules" label-width="80px">
              <el-row>

                <el-col :span="12">
                  <el-form-item label="用户名" prop="userName">
                    <el-input
                      placeholder="请输入用户名称"
                      v-model="userForm.userName"
                      clearable>
                    </el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="用户昵称" prop="nickName">
                    <el-input
                      placeholder="请输入用户昵称"
                      v-model="userForm.nickName"
                      clearable>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="密码" prop="password">
                    <el-input
                      placeholder="请输入密码"
                      v-model="userForm.password"
                      show-password
                      clearable>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="性别" >
                    <el-select v-model="userForm.sex" clearable placeholder="请选择">
                      <el-option label="男" value="0"></el-option>
                      <el-option label="女" value="1"></el-option>
                      <el-option label="未知" value="2"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="邮箱" prop="email">
                    <el-input
                      placeholder="请输入邮箱地址"
                      v-model="userForm.email"
                      clearable>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="电话" prop="phonenumber">
                    <el-input
                      placeholder="联系方式"
                      v-model="userForm.phonenumber"
                      clearable>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="角色">
                    <el-select v-model="roles" multiple placeholder="请选择" @change="selectRoles"  value-key="value" >
                      <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="备注" prop="remark">
                    <el-input
                      type="textarea"
                      autosize
                      placeholder="备注"
                      v-model="userForm.remark">
                    </el-input>
                  </el-form-item>
                </el-col>

              </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editFlag = false">取 消</el-button>
                <el-button type="primary" @click="edit">确 定</el-button>
            </span>
        </el-dialog>
    </div>

</template>

<script>
  import Pagination from '@/components/Pagination'
    import Treeselect from '@riophae/vue-treeselect'
  import { Notification, MessageBox, Message } from 'element-ui'
    import '@riophae/vue-treeselect/dist/vue-treeselect.css'
    import {userList,saveUser,deleteUser,exportTemplate,importUser,exportUser,getEditUser,editUser,getAllRoleList,getAllRolByUserId} from "@/api/user/user"
    export default {
        name: "index",
        inject: ['reload'],
        components:{
            Pagination
        },
        data() {
            return {
                formInline: {
                    user: '',
                    region: ''
                },
                // 总条数
                total: 0,
                searchParams:{
                    userName:null,
                    phone:null,
                    email:null,
                    createTime:null,
                    pageNum: 1,
                    pageSize: 10,
                },
                multipleSelection: [],
                searchDto:{},
                userList:[],
                addFlag:false,
                userForm:{
                    userName:"",
                    nickName:"",
                    password:"",
                    avatar:"",
                    sex:"",
                    email:"",
                    phonenumber:"",
                    isAdmin:"",
                    remark:"",
                    roleIds:[],
                    userId:""

                },
                imageUrl: '',
                rules: {
                    userName: [
                        {required: true, message: "用户名不能为空", trigger: "blur"}
                    ],
                  password: [
                        {required: true, message: "密码不能为空", trigger: "blur"}
                    ],
                    isAdministrator: [
                        {required: true, message: "是否管理员字段不能为空", trigger: "blur"}
                    ],
                    email: [
                        {required: true, message: "邮箱不能为空", trigger: "blur"},
                        {
                          type: "email",
                          message: "'请输入正确的邮箱地址",
                          trigger: ["blur", "change"]
                        }
                    ],
                  phonenumber: [
                        {required: true, message: "电话不能为空", trigger: "blur"},
                        {
                          pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                          message: "请输入正确的手机号码",
                          trigger: "blur"
                        }
                    ],
                },
                deleteFlag:true,
                /**
                 * 控制删除按钮
                 */
                deleteShowFlag:false,
                arrObj : [],
                exportFlag:false,
                editFlag:false,
                delFlag:false,
                value: '0',
                editUserInfo:{
                  userName:"",
                  nickName:"",
                  password:"",
                  avatar:"",
                  sex:"",
                  email:"",
                  phonenumber:"",
                  isAdmin:"",
                  remark:"",
                  userId:""
                },
                currentPage: 1,
                options: [],
                value1: [],
                value2: [],
                roles:[],
              roleVosObj:[],
              // 遮罩层
              loading: true,
            }
        },
        created(){
          this.getUserLists();
        },
        methods: {
            getUserLists() {
              this.loading = true;
              userList(this.searchParams).then(res =>{
                this.userList = res.data.result;
                this.total = res.data.total;
                this.loading = false;
              })
            },
            handleEdit(index, row) {
                this.editFlag = true;
              getAllRoleList().then(res=>{
                this.options = res.data;
              });
              this.roles = [];
                getEditUser(row.userId).then(res=>{
                  console.log(res);
                  this.userForm = res.data;
                  if (res.data.roles!=null) {
                   this.roles = res.data.roleVosObj;

                  }
                })

            },
            handleDelete(index, row) {
                this.arrObj.push(row.userId);
                deleteUser(this.arrObj).then(res=>{
                    console.log(this.arrObj);
                    if (res.code===200) {
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.deleteFlag = true;
                        this.reload();
                    }
                });
            },
            onSubmit() {
              this.getUserLists();
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
                if (val.length>0) {
                    this.deleteFlag = false;
                    let deleteArray = this.multipleSelection.filter(item=>item.isAdmin!==0);
                    this.multipleSelection.forEach((item,index,arr)=>{
                   if (0===item.isAdmin) {
                       this.$notify({
                           title: '警告',
                           message: '管理员不能删除，请重新选择',
                           type: 'warning'
                       });
                       this.deleteFlag = true;
                   }
               },
                deleteArray.forEach((item,index,arr)=>{
                    this.arrObj.push(item.userId);
                })
               );
                }else {
                    this.deleteFlag = true;
                    this.$notify({
                        title: '警告',
                        message: '请选中记录删除',
                        type: 'warning'
                    });
                }
            },


            add() {
              this.reset();
              this.roles = [];
              this.addFlag = true;
              getAllRoleList().then(res=>{
                this.options = res.data;
              })
            },
            addSubmit() {
              console.log(this.userForm);
                saveUser(this.userForm).then(res=>{
                    if (res.code===200) {
                        this.$message({
                            message: '新增成功',
                            type: 'success'
                        });
                        this.addFlag = false;
                        this.reload();
                    }
                    console.log(res);
                })
            },

            deleteBatch() {
                deleteUser(this.arrObj).then(res=>{
                    if (res.code===200) {
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.deleteFlag = true;
                        this.reload();
                    }
                });

            },
            importExcel() {
                this.exportFlag = true;
            },
            excelSubmit() {

            },
            importTemplate() {

               exportTemplate().then(res=>{
                   let blob = new Blob([res],{type: 'application/vnd.ms-excel'});
                   let objUrl = URL.createObjectURL(blob);
                   window.location.href = objUrl;
                   URL.revokeObjectURL(objUrl); // 释放URL 对象
               }).catch(error=>{
                 console.log(error);
               })
            },
            beforeUpload(file) {
                let formData = new FormData();
                formData.append('file',file);
                importUser(formData).then(res=>{
                  console.log(res);
                  if (res.code===200) {
                    MessageBox.confirm(
                      '导入用户成功',
                      '系统提示',
                      {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'success'
                      }
                    ).then(()=>{
                      this.reload();
                    });
                  }
                })
            },
            exportExcel() {
                exportUser().then(res=>{
                    /*console.log(res);*/
                    let blob = new Blob([res], { type: 'application/vnd.ms-excel' });
                    let downloadElement = document.createElement('a');
                    let href = window.URL.createObjectURL(blob); //创建下载的链接
                    downloadElement.href = href;
                    downloadElement.download = 'result.xls'; //下载后文件名
                    document.body.appendChild(downloadElement);
                    downloadElement.click(); //点击下载
                    document.body.removeChild(downloadElement); //下载完成移除元素
                    window.URL.revokeObjectURL(href); //释放掉blob对象

                })
            },
            edit() {
                editUser(this.userForm).then(res=>{
                    if (res.code===200) {
                        this.$message({
                            message: '修改成功',
                            type: 'success'
                        });
                        this.editFlag = true;
                        this.reload();
                    }
                })

            },
            selectRoles(data) {
              let arr = [];
              for (let item of data) {
                arr.push(item.value);
              }
              this.userForm.roleIds = arr;
            },
          removeRoles(data) {
            console.log(data);
          },
          reset() {
           /* userForm:{
              userName:"",
                nickName:"",
                password:"",
                avatar:"",
                sex:"",
                email:"",
                phonenumber:"",
                isAdmin:"",
                remark:"",
                roleIds:[],
                userId:""
            },*/
           /* this.resetForm("userForm");*/
            let params = Object.keys(this.userForm).forEach(key => (this.userForm[key] = ""));

          }
        }
    }
</script>

<style lang="scss" >
    .container {
        display: flex;
        flex-direction: column;
    }
    .page {
        display: flex;
        flex-direction: row;
        margin-left: 91%;
        margin-top: 1%;
    }
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
    .el-switch__label--left{
        position: relative;
        left: 46px;
        color: #fff;
        z-index: -1111;
    }
    .el-switch__label--right{
        position: relative;
        right: 46px;
        color: #fff;
        z-index: -1111;
    }
    .el-switch__label.is-active{
        z-index: 1111;
        color: #fff;
    }
    .el-switch__label--left{
        position: relative;
        left: 46px;
        color: #fff;
        z-index: -1111;
    }
    .el-switch__label--right{
        position: relative;
        right: 46px;
        color: #fff;
        z-index: -1111;
    }
    .el-switch__label--right.is-active{
        z-index: 1111;
        color: #fff !important;
    }
    .el-switch__label--left.is-active{
        z-index: 1111;
        color: #9c9c9c !important;
    }
</style>
